package com.jbit.examSystem.service.impl;

import com.jbit.examSystem.dao.TestPaperDao;
import com.jbit.examSystem.exception.AddException;
import com.jbit.examSystem.exception.RemoveException;
import com.jbit.examSystem.pojo.Question;
import com.jbit.examSystem.pojo.TestPaper;
import com.jbit.examSystem.param.TestPaperParam;
import com.jbit.examSystem.pojo.TestPaperDetail;
import com.jbit.examSystem.service.TestPaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class TestPaperServiceImpl implements TestPaperService {
    @Autowired
    private TestPaperDao testPaperDao;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public List<TestPaper> list(TestPaperParam param) {
        List<TestPaper> testPapers = testPaperDao.list(param);
        return testPapers;
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public TestPaper findById(int id) {
        TestPaper testPaper = testPaperDao.selectById(id);
        return testPaper;
    }

    @Override
    public void add(TestPaper testPaper){
        testPaperDao.insert(testPaper);
    }

    @Override
    public void modify(TestPaper testPaper) {
        testPaperDao.update(testPaper);
    }

    @Override
    public void remove(Integer[] ids) throws RemoveException {
        try {
            for (int i = 0; i < ids.length; i++) {
                testPaperDao.delete(ids[i]);
            }
        } catch (RemoveException e) {
            throw new RemoveException(e.getMessage());
        }
    }

    @Override
    public void addDetail(Integer[] questionIds,Integer testPaperId) {
        for (Integer questionId : questionIds) {
            testPaperDao.insertDetail(questionId,testPaperId);
        }
    }

    @Override
    public List<Question> getQuestionByTestPaperId(Integer testPaperId) {
        List<Question> questions = testPaperDao.getQuestionByTestPaperId(testPaperId);
        return questions;
    }

}
